package com.zhang.publisher.controller;

import com.zhang.publisher.bean.KeywordStats;
import com.zhang.publisher.bean.ProductStats;
import com.zhang.publisher.bean.ProvinceStats;
import com.zhang.publisher.bean.VisitorStats;
import com.zhang.publisher.service.KeywordStatsService;
import com.zhang.publisher.service.ProductStatsService;
import com.zhang.publisher.service.ProvinceStatsService;
import com.zhang.publisher.service.VisitorStatusService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * @title: 大屏展示Controller
 * @author: zhang
 * @date: 2022/3/17 15:05
 */
@RestController
@RequestMapping("/api/sugar")
public class SugarController {

    @Autowired
    private ProductStatsService productStatsService;

    @Autowired
    private ProvinceStatsService provinceStatsService;

    @Autowired
    private VisitorStatusService visitorStatusService;

    @Autowired
    private KeywordStatsService keywordStatsService;

    @RequestMapping("/gmv")
    public String getGmv(@RequestParam(value = "data", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }
        BigDecimal gmv = productStatsService.getGmv(date);
        String json = "{\"status\":0,\"data\":" + gmv + "}";
        return json;
    }

    @RequestMapping("/trademark")
    public String topTrademark(@RequestParam(value = "data", defaultValue = "0") Integer date,
                               @RequestParam(value = "limit", defaultValue = "5") Integer limit) {
        if (date == 0) {
            date = now();
        }
        List<ProductStats> productStats = productStatsService.selectProductStatsByTrademark(date, limit);
        ArrayList<String> trademarkList = new ArrayList<>();
        ArrayList<BigDecimal> amountList = new ArrayList<>();

        for (ProductStats productStat : productStats) {
            trademarkList.add(productStat.getTm_name());
            amountList.add(productStat.getOrder_amount());
        }

        String json = "{ " +
                "\"status\":0," +
                "\"data\":" +
                "{\"categories\" : [\"" +
                StringUtils.join(trademarkList, "\",\"") + "\"],\"series\":[" +
                "{ \"name\":\"商品品牌\", \"data\":[" + StringUtils.join(amountList, ",") + "]}]}" +
                "}";

        return json;
    }


    @RequestMapping("/category")
    public Map topCategory(@RequestParam(value = "data", defaultValue = "0") Integer date,
                           @RequestParam(value = "limit", defaultValue = "10") Integer limit) {

        if (date == 0) {
            date = now();
        }
        List<ProductStats> productStats = productStatsService.selectProductStatsByCategory3(date, limit);
       /* StringBuilder jsonstr = new StringBuilder("{ \"status\": 0 ,");
        jsonstr.append("\"data\": [");
        for (int i = 0; i < productStats.size(); i++) {
            jsonstr.append("{\"name\":" + "\"" + productStats.get(i).getCategory3_name() + "\",");
            jsonstr.append("\"value\":" + productStats.get(i).getOrder_amount() + "}");
            if (i < productStats.size() - 1) {
                jsonstr.append(",");
            }
        }
        jsonstr.append("] }");*/

        Map resMap = new HashMap();
        resMap.put("status", 0);
        ArrayList dataList = new ArrayList();
        for (ProductStats productStat : productStats) {
            Map dataMap = new HashMap();
            dataMap.put("name", productStat.getCategory3_name());
            dataMap.put("value", productStat.getOrder_amount());
            dataList.add(dataMap);
        }
        resMap.put("data", dataList);
        return resMap;
    }


    @RequestMapping("/spu")
    public String topSpu(@RequestParam(value = "data", defaultValue = "0") Integer date,
                         @RequestParam(value = "limit", defaultValue = "10") Integer limit) {

        if (date == 0) {
            date = now();
        }

        List<ProductStats> productStatsBySPUList = productStatsService.selectProductStatsBySpu(date, limit);
        //初始化表头信息
        StringBuilder jsonBuilder = new StringBuilder("{" +
                "\"status\": 0," +
                "\"data\": {" +
                "\"columns\": [{" +
                "\"name\": \"商品SPU名称\"," +
                "\"id\": \"spu_name\"" +
                "}," +
                "{" +
                "\"name\": \"交易额\"," +
                "\"id\": \"order_amount\"" +
                "}," +
                "{" +
                "\"name\": \"订单数\"," +
                "\"id\": \"order_ct\"" +
                "}" +
                "]," +
                "\"rows\": [");

        for (int i = 0; i < productStatsBySPUList.size(); i++) {
            ProductStats productStats = productStatsBySPUList.get(i);

            jsonBuilder.append("{" +
                    "\"spu_name\": \"" + productStats.getSpu_name() + "\"," +
                    "\"order_amount\":" + productStats.getOrder_amount() + "," +
                    "\"order_ct\":" + productStats.getOrder_ct() + "}"
            );
            if (i < productStatsBySPUList.size() - 1) {
                jsonBuilder.append(",");
            }
        }

        jsonBuilder.append("]}}");

        return jsonBuilder.toString();
    }

    @RequestMapping("/province")
    public String provinceStats(@RequestParam(value = "data", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }

        List<ProvinceStats> provinceStats = provinceStatsService.getProvinceStats(date);
        StringBuilder jsonStr = new StringBuilder("{\"status\": 0," +
                "\"data\": {" +
                "\"mapData\": [");

        for (int i = 0; i < provinceStats.size(); i++) {
            ProvinceStats stats = provinceStats.get(i);
            jsonStr.append("{\"name\":" + "\"" + stats.getProvince_name() + "\",");
            jsonStr.append("\"count\":" + stats.getOrder_count() + ",");
            jsonStr.append("\"value\":" + stats.getOrder_amount() + "}");
            if (i < provinceStats.size() - 1) {
                jsonStr.append(",");
            }
        }
        jsonStr.append("],");
        jsonStr.append("\"countName\":\"下单数\",");
        jsonStr.append("\"valueName\":\"交易额\"");
        jsonStr.append("}}");

        return jsonStr.toString();
    }


    @RequestMapping("/visitor")
    public String vieitorStats(@RequestParam(value = "data", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }


        List<VisitorStats> visitorStats = visitorStatusService.getVisitorStats(date);
        VisitorStats newVisitor = new VisitorStats();
        VisitorStats oldVisitor = new VisitorStats();
        for (VisitorStats visitorStat : visitorStats) {
            if (visitorStat.getIs_new().equals("1")) {
                newVisitor = visitorStat;
            } else {
                oldVisitor = visitorStat;
            }
        }

        StringBuilder jsonStr = new StringBuilder("{" +
                "  \"status\": 0," +
                "  \"data\": {" +
                "    \"total\": 5," +
                "    \"columns\": [" +
                "      {" +
                "        \"name\": \"类别\"," +
                "        \"id\": \"subsys\"" +
                "      }," +
                "      {" +
                "        \"name\": \"新用户\"," +
                "        \"id\": \"new\"" +
                "      }," +
                "      {" +
                "        \"name\": \"老用户\"," +
                "        \"id\": \"old\"" +
                "      }" +
                "    ]," +
                "    \"rows\": [" +
                "{" +
                "  \"subsys\": \"用户数\"," +
                "  \"new\": " + newVisitor.getUv_ct() + "," +
                "  \"old\": " + oldVisitor.getUv_ct() +
                "  }," +
                "  {" +
                "  \"subsys\": \"总访问页面数\"," +
                "  \"new\": " + newVisitor.getPv_ct() + "," +
                "  \"old\": " + oldVisitor.getPv_ct() +
                "   }," +
                "  {" +
                "  \"subsys\": \"跳出率(%)\"," +
                "  \"new\": " + newVisitor.getUjRate() + "," +
                "  \"old\": " + oldVisitor.getUjRate() +
                "   }," +
                "  {" +
                "  \"subsys\": \"平均在线时长(秒)\"," +
                "  \"new\": " + newVisitor.getDurPerSv() + "," +
                "  \"old\": " + oldVisitor.getDurPerSv() +
                "   }," +
                "  {" +
                "  \"subsys\": \"平均访问页面人数(人次)\"," +
                "  \"new\": " + newVisitor.getPvPerSv() + "," +
                "  \"old\": " + oldVisitor.getPvPerSv() +
                "   }" +
                "    ]" +
                "  }" +
                "}");


        return jsonStr.toString();
    }


    @RequestMapping("/hr")
    public String vieitorStatsByhr(@RequestParam(value = "data", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }
        List<VisitorStats> visitorStatsList = visitorStatusService.getVisitorStats(date);
        StringBuilder jsonStr = new StringBuilder("{\"status\": 0," +
                "\"data\":{");
        //因为有的小时可能没有数据，为了把每个小时都展示出来，我们创建一个数组，用来保存每个小时对应的访问情况
        VisitorStats[] visitorStatsArr = new VisitorStats[24];
        for (VisitorStats visitorStats : visitorStatsList) {
            visitorStatsArr[visitorStats.getHr()] = visitorStats;
        }

        //定义存放小时、uv、pv、新用户的List集合
        List<String> hrList = new ArrayList<>();
        List<Long> uvList = new ArrayList<>();
        List<Long> pvList = new ArrayList<>();
        List<Long> newVisitorList = new ArrayList<>();

        for (int i = 0; i <= 23; i++) {
            VisitorStats visitorStats = visitorStatsArr[i];
            if (visitorStats != null) {
                uvList.add(visitorStats.getUv_ct());
                pvList.add(visitorStats.getPv_ct());
                newVisitorList.add(visitorStats.getNew_uv());
            } else {
                uvList.add(0L);
                pvList.add(0L);
                newVisitorList.add(0L);
            }
            //小时为不足两位时候，前面补0
            hrList.add(String.format("%02d", i));
        }

        jsonStr.append("\"categories\":[\"" + StringUtils.join(hrList, "\",\"") + "\"],");
        jsonStr.append("\"series\":[{\"name\":\"pv\",\"data\":[" + StringUtils.join(pvList, ",") + "]},");
        jsonStr.append("{\"name\":\"uv\",\"data\":[" + StringUtils.join(uvList, ",") + "]},");
        jsonStr.append("{\"name\":\"新用户\",\"data\":[" + StringUtils.join(newVisitorList, ",") + "]}]}}");

        return jsonStr.toString();
    }


    @RequestMapping("/keyword")
    public String getKeyword(@RequestParam(value = "data", defaultValue = "0") Integer date,
                             @RequestParam(value = "limit", defaultValue = "10") Integer limit) {

        if (date == 0) {
            date = now();
        }
        List<KeywordStats> keywordStatsList = keywordStatsService.getKeyword(date, limit);
        StringBuilder jsonStr = new StringBuilder("{\"status\": 0," +
                "\"data\":[");
        for (int i = 0; i < keywordStatsList.size(); i++) {
            KeywordStats keywordStats = keywordStatsList.get(i);
            jsonStr.append("{\"name\":\"" + keywordStats.getKeyword() + "\",");
            jsonStr.append("\"value\":" + keywordStats.getCt() + "}");
            if (i < keywordStatsList.size() - 1) {
                jsonStr.append(",");
            }
        }
        jsonStr.append("]}");

        return jsonStr.toString();
    }


    private Integer now() {
        String date = DateFormatUtils.format(new Date(), "yyyyMMdd");
        return Integer.valueOf(date);
    }
}
